package com.jyc.controller;

import com.jyc.entity.ck.UserInfo;
import com.jyc.entity.ck.UserInfoExample;
import com.jyc.mapper.ck.UserInfoMapper;
import com.jyc.util.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin("*")
public class LoginController {
    @Autowired(required = false)
    private UserInfoMapper userInfoMapper;

    @GetMapping("/login")
    public HttpResult login( UserInfo userInfo) {
        UserInfoExample example = new UserInfoExample();
        UserInfoExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(userInfo.getUsername());
        criteria.andPasswordEqualTo(userInfo.getPassword());
        List<UserInfo> userInfos = userInfoMapper.selectByExample(example);
        if (userInfos == null || userInfos.size() <= 0) {
            return HttpResult.error(401,"用户名密码不正确");
        }
        return HttpResult.ok(userInfos.get(0));
    }

    @GetMapping("register")
    public HttpResult register(UserInfo userInfo) {
        userInfo.setRole("admin");
        if (userInfo.getUsername() != null) {
            UserInfoExample userInfoExample = new UserInfoExample();
            UserInfoExample.Criteria criteria = userInfoExample.createCriteria();
            criteria.andUsernameEqualTo(userInfo.getUsername());
            List<UserInfo> userInfos = userInfoMapper.selectByExample(userInfoExample);
            if (userInfos.size() == 0) {
                userInfo.setAddtime(new Date());
                userInfoMapper.insert(userInfo);
                return HttpResult.ok();
            }else {
                return HttpResult.error(400,"用户名重复");
            }
        }else {
            return HttpResult.error(400,"请输入用户名");
        }
    }
}
